package com.study.rabbitmq;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.net.URI;

@Configuration
@ComponentScan("com.study.rabbitmq")
@EnableRabbit//开启rabbitmq监听模式
public class RabbitConfig {

    @Bean
    public ConnectionFactory getConnectionFactory(){
        ConnectionFactory connectionFactory = new CachingConnectionFactory(URI.create("amqp://root:123456@192.168.181.131:5672/%2f"));
        return connectionFactory;
    }


    @Bean
    @Autowired
    public RabbitTemplate getRabbitTemplate(ConnectionFactory connectionFactory){

        return new RabbitTemplate(connectionFactory);
    }


    @Bean
    @Autowired
    public RabbitAdmin getRabbitAdmin(ConnectionFactory connectionFactory){
        return new RabbitAdmin(connectionFactory);
    }

    @Bean
    public Queue getQueue(){
        Queue queue = QueueBuilder.nonDurable("queue.anno").build();
        return queue;

    }

    @Bean("rabbitListenerContainerFactory")

    public SimpleRabbitListenerContainerFactory getSimpleMessageListenerContainer(ConnectionFactory connectionFactory){

        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setConcurrentConsumers(10);
        factory.setMaxConcurrentConsumers(100);
        //按批次消费消息
        factory.setBatchSize(10);
        return factory;
    }

}
